﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using HotCopperUserScanService.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace HotCopperUserScanService.Tests
{
    [TestClass]
    public class PostsTimerTests
    {

        [TestInitialize]
        public void TestInitialize()
        {
        }

        [TestCleanup]
        public void TestCleanup()
        {
            
        }

        [TestMethod]
        [Timeout(5000)]
        public void Timer_Exception_RecordsInErrorCollection()
        {
            using (ShimsContext.Create())
            {
                var expectedException = new ApplicationException("Expecting this Message");
                var stockForum = new StubIStockForumBrowser()
                {
                    LoginStringStringString = (u, p, url) => { throw expectedException; }
                };
                ShimPostsDatabase.RetrieveStringInt32 = (uname, postCount) => new List<Post>();
                var errorEvent = false;
                var postsTimer = new PostsTimer(stockForum);
                postsTimer.NewPostsEvent += (sender, posts) => { errorEvent = true; };
                postsTimer.Start();
                while (!postsTimer.Errors.Any())
                {
                    Thread.Sleep(20);
                }
                Assert.IsTrue(postsTimer.Errors.Any());
                Assert.AreEqual(expectedException.Message, postsTimer.Errors.First());
                Assert.IsTrue(errorEvent);
            }
        }
    }
}
